/**
 * Cookie工具类，用于管理cookie的存取操作
 */

/**
 * 设置cookie
 * @param name cookie名称
 * @param value cookie值
 * @param days 过期天数
 */
export const setCookie = (name: string, value: string, days: number = 7): void => {
  const date = new Date();
  date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  const expires = `expires=${date.toUTCString()}`;
  document.cookie = `${name}=${value};${expires};path=/`;
};

/**
 * 获取cookie
 * @param name cookie名称
 * @returns cookie值或null
 */
export const getCookie = (name: string): string | null => {
  const nameEQ = `${name}=`;
  const ca = document.cookie.split(';');
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) === ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
  }
  return null;
};

/**
 * 删除cookie
 * @param name cookie名称
 */
export const deleteCookie = (name: string): void => {
  document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`;
};

/**
 * 设置用户信息到cookie
 * @param userInfo 用户信息对象
 * @param days 过期天数，默认7天
 */
export const setUserInfo = (userInfo: any, days: number = 7): void => {
  const userInfoStr = JSON.stringify(userInfo);
  setCookie('admin_user_info', userInfoStr, days);
};

/**
 * 从cookie获取用户信息
 * @returns 用户信息对象或null
 */
export const getUserInfo = (): any | null => {
  const userInfoStr = getCookie('admin_user_info');
  if (userInfoStr) {
    try {
      return JSON.parse(userInfoStr);
    } catch (error) {
      console.error('解析用户信息失败:', error);
      return null;
    }
  }
  return null;
};

/**
 * 删除用户信息cookie
 */
export const deleteUserInfo = (): void => {
  deleteCookie('admin_user_info');
};